import React, { useEffect, useRef, useState } from "react";


function Canvas() {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  // const images = useRef<
  //   { src: string; x: number; y: number; width: number; height: number }[]
  // >([]).current;
  const [images,setImages]=useState<{src:string;x:number;y:number;width:number;height:number}[]>([])
  const [selectedImageIndex, setSelectedImageIndex] = useState<number | null>(
    null
  );
  const [isDragging,setIsDragging]=useState(false);
  const [offset,setOffset]=useState<{x:Number;y:number}|null>(null);
//   删除选中的图片
  const deleteSelectedImage=()=>{
    if(selectedImageIndex!==null){
      const updatedImages=[...images];
      updatedImages.splice(selectedImageIndex,1)
        // images.splice(selectedImageIndex,1)
        // setSelectedImageIndex(null)
        setImages(updatedImages)
        setSelectedImageIndex(null)
        const context=canvasRef.current!.getContext('2d');
        if(context){
          drawImages(context)
        }
        // drawImages(canvasRef.current!.getContext('2d')!)
    }
  }
  useEffect(()=>{
    const canvas=canvasRef.current;
    if(!canvas) return ;
    const context=canvas.getContext('2d')
    if(!context) return 
    canvas.width=1000
    canvas.height=600
    drawImages(context)
  },[])
  const drawImages=(context:CanvasRenderingContext2D)=>{
    context.clearRect(0,0,context.canvas.width,context.canvas.height)
    images.forEach(({src,x,y,width,height})=>{
        const img=new Image();
        img.src=src;
        img.onload=()=>{
            context.drawImage(img,x,y,width,height)
        }
    })
  }
  const handleDrop=(event:DragEvent)=>{
    event.preventDefault();
    const src=event.dataTransfer.getData('text/plain');
    const canvas=canvasRef.current;
    if(canvas){
        const rect=canvas.getBoundingClientRect();
        const x=event.clientX-rect.left;
        const y=event.clientY-rect.top;
        const img=new Image();
        img.src=src;
        img.onload=()=>{
            // images.push({src,x,y,width:img.width,height:img.height})
            const newImage={src,x,y,width:img.width,height:img.height};
            const context=canvas.getContext('2d')
            if(context){
                drawImages(context)
            }
        }
    }
  }
  const handleDragOver=(event:DragEvent)=>{
    event.preventDefault();
  }
  const handleCanvasClick=(event:React.MouseEvent<HTMLDivElement>)=>{
    const canvas=canvasRef.current;
    if(!canvas) return ;
    const rect=canvas.getBoundingClientRect();
    const x=event.clientX-rect.left;
    const y=event.clientY-rect.top;
    images.forEach((image,index)=>{
      if(x>=image.x&&x<=image.x+image.width&&y>=image.y&&y<=image.y+image.height){
        setSelectedImageIndex(index)
      }
    })
  }
  const handleMouseDown=(event:React.MouseEvent<HTMLDivElement>)=>{
    const canvas=canvasRef.current;
    if(!canvas||selectedImageIndex===null) return 
    const rect=canvas.getBoundingClientRect();
    const x=event.clientX-rect.left;
    const y=event.clientY-rect.top;
    const img=images[selectedImageIndex];
    if(x>=img.x&&x<=img.x+img.width&&y>=img.y&&y<=img.y+img.height){
      setIsDragging(true)
      setOffset({x:x-img.x,y:y-img.y})
    }
  }
  const handleMouseMove=(event:React.MouseEvent<HTMLDivElement>)=>{
    if(isDragging&&selectedImageIndex!==null){
      const canvas=canvasRef.current;
      if(!canvas) return 
      const rect=canvas.getBoundingClientRect();
      const x=event.clientX-rect.left;
      const y=event.clientY-rect.top;
      const img=images[selectedImageIndex];
      img.x=x-offset.x;
      img.y=y-offset.y;
      const context=canvas.getContext('2d')
      if(context){
        drawImages(context)
      }
    }
  }
  const handleMouseUp = (event: React.MouseEvent<HTMLDivElement>) => {
    if (isDragging && selectedImageIndex !== null) {
      const canvas = canvasRef.current;
      if (!canvas) return;

      const rect = canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;

      const img = images[selectedImageIndex];
      img.x = x - offset.x;
      img.y = y - offset.y;

      setIsDragging(false);
      setOffset(null);
      setSelectedImageIndex(null);

      const context = canvas.getContext('2d');
      if (context) {
        drawImages(context);
      }
    }
  };
  return (
    <div>
      <div style={{width:'1000px',height:'600px',background:'#f3f3f3',marginLeft:'120px',overflow:'hidden',position:'relative',marginTop:'150px'}}></div> {/* 传递删除函数 */}
      <div
        style={{position:'absolute',left:'415px',top:'60px'}}
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onClick={handleCanvasClick}
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
      >
        <canvas ref={canvasRef} />
      </div>
    </div>
  );
}

export default Canvas;
